package de.doumen.gpx.utils;

import java.util.Iterator;
import java.util.Set;


import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;


import de.doumen.gpx.GpxTrackpoint;

public class GpxHandler extends DefaultHandler {

	private Set processors; 
	
	public Set getProcessors() {
		return processors;
	}

	public void setProcessors(Set processors) {
		this.processors = processors;
	}

	private GpxTrackpoint trkpt = null;
	private StringBuffer sb = null;
	
	
	
	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		String s = new String( ch, start, length );
	    if( sb == null )
	      sb = new StringBuffer( s );
	    else
	      sb.append( s );
	}

	@Override
	public void endDocument() throws SAXException {
		// TODO Auto-generated method stub
		super.endDocument();
	}

	@Override
	public void endElement(String uri, String localName, String name)
			throws SAXException {
		if ( "trkpt".equals(localName))
		{
	          for (Iterator iterator = this.processors.iterator(); iterator.hasNext(); ) {
	              GpxProcessor p = (GpxProcessor)iterator.next();
	              p.process(trkpt);
	          }
	          trkpt = null;
		}
		else
		{
			if (trkpt!=null)
			{
				trkpt.addData(localName, sb.toString());
				sb = null;
			}
		}
		
		super.endElement(uri, localName, name);
	}

	@Override
	public void startDocument() throws SAXException {
		// TODO Auto-generated method stub
		super.startDocument();
	}

	@Override
	public void startElement(String uri, String localName, String name,
			Attributes attrs) throws SAXException {
		
		if ( "trkpt".equals(localName))
		{
			trkpt = new GpxTrackpoint();
			if( attrs != null )
		    {
		      for( int i=0; i<attrs.getLength(); i++ )
		      {
		        String aName = attrs.getLocalName( i ); // Attr name
		        if( "".equals( aName ) )  aName = attrs.getQName( i );
		        if ( "lat".equals(aName)) trkpt.setLatitude( Double.valueOf(attrs.getValue(i)));
		        if ( "lon".equals(aName)) trkpt.setLongitude( Double.valueOf(attrs.getValue(i)));
		      }
		    }
		}
		super.startElement(uri, localName, name, attrs);
	}

	
}
